package com.hrt.datasender.dataschedule;

import java.util.List;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.hrt.datasender.datadao.model.BcSendPlatformModel;
import com.hrt.datasender.datadao.service.BcSendPlatformService;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.MqModel;
import com.hrt.datasender.mq.model.PacketModel;
import com.hrt.datasender.process.indentity.IMessageIdentity;
import com.hrt.datasender.process.indentity.IMessageIdentityLoader;
import com.hrt.datasender.process.indentity.hj212.MessageModel;
import com.hrt.datasender.process.strategy.IProcessStrategy;
import com.hrt.datasender.process.strategy.ProcessStrategyLoader;

/**
 * 解析从中心站过来的数据
 * 
 * @author gislin
 *
 */
public class DataReceiveScheduler {

    private static ILog log;

    public static void start() {

        log = MyLog.getInstance().getLogger(DataReceiveScheduler.class);

        MqKit.consumeMsgFromCenterStationMQ(new MqKit.MsgListener() {
            @Override
            public void onReceive(MqModel mqModel) {

                try {
                    PacketModel packetModel = (PacketModel) mqModel;

                    String ip = packetModel.getIp();
                    String port = packetModel.getPort();

                    BcSendPlatformModel platform = BcSendPlatformService.getInstance().getPlatformInfo(ip, port);

                    String protocolId = platform.getTransportProtocolId();
                    String platformId = platform.getPlatformId();

                    IMessageIdentity protocol = IMessageIdentityLoader.getInstance().getProtocolById(protocolId);

                    List<MessageModel> datas = protocol.decode(packetModel.getMsg());

                    for (MessageModel data : datas) {
                        String commandId = data.getCommandId();

                        try {
                            IProcessStrategy processStrategy = ProcessStrategyLoader.getInstance()
                                    .getStrategyByCommandId(platformId, commandId);

                            if (processStrategy == null) {
                                log.error("平台" + platform.getName() + "," + commandId + "无对应解析器");
                                continue;
                            }

                            processStrategy.decode(data, platform);

                            log.info("平台" + platform.getName() + ",命令" + commandId + "解析成功");

                        }
                        catch (Exception e) {
                            log.error("平台" + platform.getName() + "," + commandId + "解析出错", e);
                        }
                    }

                } 
                catch (Exception e) {
                    log.error("解析中心站数据出错", e);
                }
            }
        });

    }

}
